package com.woniu.exception;

import com.woniu.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(OutpatientException.class)
    public Result handMedicalCareException(OutpatientException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return Result.bulid().setCode(e.getCode()).setMessage(e.getMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public Result handConstraintViolationException(ConstraintViolationException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return Result.bulid().setCode(9527).setMessage(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        StringBuffer stringBuffer = new StringBuffer();
        for (ObjectError error : e.getBindingResult().getAllErrors()) {
            stringBuffer.append(error.getDefaultMessage());
        }
        return Result.bulid().setCode(9528).setMessage(stringBuffer.toString());
    }

}
